import sys

class Table(object):
    def __init__(self, colnames, labels=[]):
        self.colnames = colnames
        if not labels: labels = colnames
        self.labels = labels
        self.title_row = dict ( zip (colnames, labels))
        self.colwidths = dict ([(colname, len(self.title_row[colname])) for colname in self.title_row])
        self.colsep = '|'
        self.rowsep = '-'
        self.rows = []
    def addRow(self, row_d):
        for col in self.colnames:
            row_len = len(str(row_d[col]))
            if row_len > self.colwidths[col]:
                self.colwidths[col] = row_len
        self.rows.append(row_d)
    def addRows(self, row_ds):
        for row_d in row_ds:
            self.addRow(row_d)
    def render(self):
        fmt = ""
        for colname in self.colnames:
            fmt += "%%(%s)-%ds|" % (colname, self.colwidths[colname])
        fmt = '|' + fmt + '\n'
        title_row = dict ([(colname,colname) for colname in self.colnames])
        out = fmt % self.title_row
        row_len = len(out)
        hr = self.rowsep * (row_len - 1) + '\n'
        out = hr + out + hr
        sys.stdout.write(out)
        first_row = False
        for row in self.rows:
            out = fmt % row
            sys.stdout.write(out)
        sys.stdout.write(hr)

class TwoColTable(Table):
    def render(self):
        fmt = "%-25s:%s\n"
        row = self.rows[0]
        for name in self.colnames:
            sys.stdout.write(fmt % (self.title_row[name], row[name]))

if __name__ == '__main__':
    t = Table(["sr", "name", "age"], ["Sr.", "Name", "Age"])
    t.addRow(dict(sr = 0, name = "Shekhar", age = 31))
    t.addRow(dict(sr = 1, name = "Shekhar Tiwatne", age = 031))
    t.addRow(dict(sr = 2, name = "Mr. Bean", age = 2))
    t.render()
